package T0;

/**
 * @Author cheng.song
 * @create 2022/2/24 11:23
 */
public class T2两数相加 {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2,new ListNode(4,new ListNode(3)));
        ListNode l2 = new ListNode(5,new ListNode(6,new ListNode(4)));
        ListNode listNode = addTwoNumbers(l1, l2);
        while (listNode!=null){
            System.out.println(listNode.val);
            listNode=listNode.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode current = null;
        int next=0;
        while (l1!=null || l2!=null || next>0){
            int num =0;
            if(l1!=null){
                num =num+l1.val;
                l1=l1.next;
            }
            if(l2!=null){
                num =num+l2.val;
                l2=l2.next;
            }
            if(next>0){
                num = num + next--;
            }
            if(num>=10){
                num = num%10;
                next++;
            }
            if(current==null){
                current = new ListNode(num);
                head = current;
            }else{
                current.next = new ListNode(num);
                current = current.next;
            }
        }
        return head;
    }

    public static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
